package com.qfedu.knowledge.service.impl;

import com.alibaba.excel.EasyExcel;
import com.qfedu.knowledge.dao.IQuestionInfoDao;
import com.qfedu.knowledge.entity.dto.QueryDTO;
import com.qfedu.knowledge.entity.vo.QuestionInfoVO;
import com.qfedu.knowledge.service.ExportExcelService;
import com.qfedu.knowledge.util.SecurityUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName ExportExcelServiceImpl
 * @Author ykx
 * @Date 2024/5/20 10:25
 * @Version 1.0
 */
@Service
public class ExportExcelServiceImpl implements ExportExcelService {

    @Autowired
    private IQuestionInfoDao questionInfoDao;

    @Autowired
    private SecurityUtils securityUtils;

    @Override
    @SneakyThrows
    public ResponseEntity<byte[]> exportQuestion(QueryDTO queryDTO) {
        String fileName = "question.xlsx"; // 导出的文件名

        Long userId = securityUtils.getCurrentUser().getId();
        List<QuestionInfoVO> list = questionInfoDao.getQuestionInfoByPage(userId, queryDTO);

        // 创建Excel工作簿并写入数据
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, QuestionInfoVO.class).sheet("题库").doWrite(list);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
    }
}
